package com.xiaolun;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * @Author 硕鼠
 * @Date 2020/6/13 11:18
 * @Version 1.0
 * @Description 文件说明
 */

//保存用户上一次访问的时间
public class CookieDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        PrintWriter out = resp.getWriter();

        /**
         *  1. Cookie，服务器端从客户端获取。
         *  2. req.getCookies(); //返回数组，说明Cookie可能存在多个
         */
        Cookie[] cookies = req.getCookies(); //返回数组，说明Cookie可能存在多个
        //判断Cookie是否存在
        if (cookies != null){
            //如果存在怎么办
            out.write("last time:");
            for (int i = 0; i < cookies.length; i++) {
                   if (cookies[i].getName().equals("LastLoginTime")){
                       long LastLoginTime = Long.parseLong(cookies[i].getValue());
                       Date date = new Date(LastLoginTime);
                       out.write(date.toLocaleString());
                   }
            }
        }else {
            out.write("first go here");
        }
        //服务器给客户端响应一个cookie
        Cookie cookie = new Cookie("LastLoginTime", System.currentTimeMillis()+"");
        //cookie有效期为一天
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

